<template style="height: 100%;">
  <div style="height: 100%">
    <el-container style="height: 100%">
      <el-aside style="height: 100%; width: auto">
        <i
          :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"
          @click="Collapse"
        ></i>
        <el-menu
          default-active="1-4-1"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
          :collapse="isCollapse"
        >
          <el-menu-item index="0" @click="to('../Chat/Chat')">
            <i class="el-icon-chat-dot-round"></i>
            <span slot="title">聊天</span>
          </el-menu-item>
          <el-menu-item index="1" @click="to('../Chat/Friend')">
            <i class="el-icon-user"></i>
            <span slot="title">好友申请记录</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container style="height: 100%; width: 100%">
        <el-header style="background-color: gainsboro; width: 100%">
          <div style="width: 100%">
                <el-button
                  @click="
                    addGroupVisible
                      ? (addGroupVisible = false)
                      : (addGroupVisible = true)
                  "
                  >添加群聊</el-button
                >
              <el-button
                style="margin-top: 10px"
                @click="
                  () => {
                    addFriendVisible = true;
                  }
                "
                >添加好友</el-button
              >
              <div style="float: right"
                @click="
                  () =>
                    messageVisible
                      ? (messageVisible = false)
                      : (messageVisible = true)
                "
              >
                <el-avatar
                  slot="reference"
                  :src="userData.headPortrait"
                  :size="55"
                ></el-avatar>
              <el-popover
                placement="bottom"
                trigger="manual"
                v-model="messageVisible"
                class="message"
              >
                <div
                  class="messageS"
                  @click="
                    () => {
                      userDataVisible = true;
                    }
                  "
                >
                  个人信息
                </div>
                <div class="messageS" @click="exit">退出登录</div>
              </el-popover>
              </div>
          </div>
        </el-header>
        <el-main style="height: 100%">
          <router-view style="height: 100%" />
        </el-main>
      </el-container>
    </el-container>

    <el-dialog
      title="添 加 群 组"
      :visible="addGroupVisible"
      :before-close="addGroupClose"
      width="380px"
    >
      群 名 ：
      <el-input v-model="addGroupData.name" placeholder="群 名"></el-input
      ><br />
      上传群头像：
      <el-upload
        ref="addGroupData"
        class="avatar-uploader"
        :action="host + 'api/File/Uploading'"
        :show-file-list="false"
        :headers="headers"
        :on-change="change"
        :auto-upload="false"
        :on-success="beforeAvatarUpload"
      >
        <img
          v-if="addGroupData.picture"
          :src="addGroupData.picture"
          class="avatar"
        />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addGroupVisible = false">取 消</el-button>
          <el-button type="primary" @click="addGroup" :disabled="addGroupDisabled">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="个人信息"
      :visible="userDataVisible"
      :before-close="
        () => {
          userDataVisible = false;
        }
      "
      width="420px"
    >
      <div style="margin: auto; width: 35%">
        <el-avatar
          shape="square"
          :size="150"
          :src="userData.headPortrait"
        ></el-avatar>
        <div style="margin: auto; width: 100%">
          <h3>账号：{{ userData.userNumber }}</h3>
          <h3>用户名：{{ userData.name }}</h3>
          <h3>账号状态：{{ userData.statusCode }}</h3>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="搜 索 好 友"
      :visible="addFriendVisible"
      :before-close="
        () => {
          addFriendVisible = false;
        }
      "
      width="370px"
    >
      <el-input
        v-model="addFirendName"
        placeholder="请输入对方用户名"
        style="width: 240px"
      ></el-input>
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="GetUserName"
        style="width: 80px"
        >搜索</el-button
      >
      <div
        style="text-align: center; margin: 20px auto"
        v-if="addFriendData.name"
        v-loading="addFriendLoading"
      >
        <div>
          <el-tag>{{ addFriendData.name }}</el-tag>
        </div>
        <div>
          <el-avatar
            :size="150"
            style="margin-top: 20px"
            :src="addFriendData.headPortrait"
          ></el-avatar>
        </div>
        <el-input
          type="textarea"
          placeholder="打个招呼吧!"
          maxlength="30"
          show-word-limit
          v-model="addFriendData.data"
        >
        </el-input>
        <el-button type="primary" @click="addFriend">发送好友申请</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  min-height: 96%;
  width: 200px;
}
.header {
  position: absolute;
  right: 100px;
}
.message .el-popover {
  min-width: 60px;
}
.messageS {
  height: 25px;
  line-height: 25px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
  cursor: pointer;
}
</style>
<script>
import { put, del, post, get } from "./util/request";
import { RefreshToken, Exit } from "./config/Login";
import { host } from "./config/config";
import Vue from "vue";
import EventBus from "../msg";
import { CreateGroupData } from "./config/Group";
import { connectionSignalR } from "./util/signalR";
import { GetUserName } from "./config/User";
import { CreateCreateFriends } from "./config/CreateFriend";
export default {
  data() {
    return {
      addGroupData: {
        name: "",
        pictureKey: "",
        picture: "",
      },
      userDataVisible: false,
      addFriendVisible: false,
      addFriendLoading: false,
      addGroupDisabled:false,
      addFriendData: {
        data: "",
      },
      addFirendName: "",
      host: host,
      messageVisible: false,
      isCollapse: true,
      addGroupVisible: false,
      refreshToken: null,
      userData: {
        headPortrait: "",
        name: "",
      },
    };
  },
  methods: {
    addFriend() {
      if (this.addFriendData.data.length < 5) {
        this.$message.warning("打招呼信息不能少于五位哦！");
        return;
      } else if (!this.addFriendData.id) {
        this.$message.warning("错误添加");
        return;
      }
      var data = {
        beInvitedId: this.addFriendData.id,
        remark: this.addFriendData.data,
      };
      post(CreateCreateFriends, data).then((response) => {
        this.addFriendVisible = false;
        if (response.statusCode === 200) {
          this.$message.success("申请成功");
        } else {
          this.$message.error(response.message);
        }
      });
    },
    GetUserName() {
      this.addFriendLoading = true;
      get(GetUserName + "?userNumber=" + this.addFirendName).then(
        (response) => {
          this.addFriendLoading = false;
          if (response.statusCode === 200) {
            this.addFriendData = response.value;
          } else {
            this.$message.error(response.message);
          }
        }
      );
    },
    addGroup() {
      this.addGroupDisabled=true;
      this.$refs.addGroupData.submit();
      this.addGroupDisabled=false;
    },
    addGroupClose() {
      this.addGroupVisible = false;
    },
    RefreshToken() {
      var This = this;
      This.tokent();
      this.refreshToken = window.setInterval(() => {
        This.tokent();
      }, 1700000);
    },
    tokent() {
      put(RefreshToken).then((response) => {
        if (response.statusCode != 200) {
          this.$router.push({ path: "../Login/" });
        }
        console.log("刷新token", response);
      });
    },
    message() {
      var user = JSON.parse(sessionStorage.getItem("user"));
      this.userData = user;
    },
    exit() {
      connectionSignalR.off("SystemMessage");
      connectionSignalR.off("ChatData");
      connectionSignalR.stop();
      del(Exit).then((response) => {
        if (response.statusCode == 200) {
          this.$message.success("退出登录成功");
          this.Chat = null;
          sessionStorage.clear();
          this.$router.push({ path: "../Login/" });
        } else {
          this.$message.error("退出登录失败");
        }
      });
    },
    to(url) {
      this.$router.push({ path: url });
    },
    Collapse() {
      this.isCollapse ? (this.isCollapse = false) : (this.isCollapse = true);
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    change(file) {
      this.addGroupData.picture = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(response) {
      console.log("response", response);
      if (response.statusCode === 200) {
        this.addGroupData.picture = response.value.path;
        this.addGroupData.pictureKey = response.value.key;
        post(CreateGroupData, this.addGroupData).then((response) => {
          this.addGroupVisible = false;
          console.log("添加Group", response);
          if (response.statusCode === 200) {
            EventBus.$emit("ChatRefresh", { systemMarking: 2 });
            this.$message.success("添加成功");
          } else {
            this.$message.error(response.message);
          }
        });
      } else {
        this.$message.error(response.message);
      }
    },
  },
  mounted() {
    this.message();
    this.$router.push({ path: "../Chat/Chat" });
    Vue.prototype.groupDatas = [];
    connectionSignalR.start();
    Vue.prototype.connectionSignalR = connectionSignalR;
    connectionSignalR.on("ChatData", (data) => {
      for (let i = 0; i < this.groupDatas.length; i++) {
        if (this.groupDatas[i].receiving == data.receiving) {
          this.groupDatas[i].chat.push(data);
          this.groupDatas[i].count++;
          EventBus.$emit("chatData", data.receiving,data);
          break;
        }
      }
    });
    connectionSignalR.on("SystemMessage", (data) => {
      switch (data.systemMarking) {
        case 0:
          EventBus.$emit("FriendData", data);
          break;

        case 2:
          EventBus.$emit("FriendData", data);
          EventBus.$emit("ChatRefresh", data);
          break;
      }
      this.$notify.info({
        title: data.name,
        message: data.data,
      });
    });
  },
  created() {
    var user = JSON.parse(sessionStorage.getItem("user"));
    if (user == null) {
      this.$router.push({ path: "../Login/" });
      return;
    }
    this.RefreshToken();
    this.message();
    var token = sessionStorage.getItem("token");
    this.$router.push({ path: "../Chat/Chat" });
    Vue.prototype.groupDatas = [];
    Vue.prototype.headers = { Authorization: "Bearer " + token };
    
  },
};
</script>
